<template>
	<h1 class="center">Regist</h1>
	<van-form @submit="onSubmit">
		<van-cell-group inset>
			<van-field v-model="username" name="username" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' },
		  {validator: checkUserRepete, message: ''}]" />
			<van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
				:rules="[{ required: true, message: '请填写密码' }]" />
			<van-field v-model="re_password" type="password" name="repassword" label="密码" placeholder="再次输入密码密码" :rules="[{ required: true, message: '再次输入密码密码' },
		{validator: checkRepassword,message: '两次输入的密码不一致'}]" />
		</van-cell-group>
		<div style="margin: 16px;">
			<van-button round block type="primary" native-type="submit">
				提交
			</van-button>
		</div>
	</van-form>
	<div class="right side-margin">
		<!-- <p>已经有帐号了，去<router-link to="/login">登录</router-link></p> -->
		<p>已经有帐号了，去<router-link :to="{'name':'login'}">登录</router-link>
		</p>
	</div>
</template>

<script lang="ts" setup>
	import {
		ref
	} from 'vue';
	import {
		Toast
	} from 'vant';
	import 'vant/es/toast/style';
	import {
		checkUsername,
		createUser
	} from "@/api/user.ts";
	import router from '@/router'

	const username = ref('');
	const password = ref('');
	const re_password = ref('');

	const onSubmit = (values) => {
		console.log('submit', values);
		createUser(values)
			.then(res => {
				console.log(res.code)
				if (res.code != 0) {
					// 注册失败
					Toast.fail('注册失败')
					console.log("注册失败")
				} else {
					// 注册成功
					Toast.success('注册成功')
					console.log("注册成功")
					// router.push({
					// 	"name":"logn"
					// })
					router.push("/login")
				}
			})
			.catch(err => {
				console.log(err)
			})
	};

	const checkUserRepete = (val) => {
		console.log("检查用户名是否被占用")
		const params = {
			"username": val
		}

		var result = checkUsername(params)
			.then(res => {
				console.log(res)
				if (res.code != 0) {
					return `用户名已经被只占用，参考用户名...`
				}
				return true
			})
		return result
	};
	// if(username.value != re_password.value){
	// 	return false
	// }
	// return true

	const checkRepassword = (val) => {
		console.log("检查两次密码是否一致")
		if (password.value != re_password.value) {
			return false
		}
		return true
	}

	// function onSubmit(values){
	// 	console.log('submit', values);
	// }
</script>

<style>
</style>
